package com.lib.common.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;

/**
 * @author 一叶丶枫凌
 * Created on 2017-07-18 10:38
 */
public class RightMenuScrollView extends HorizontalScrollView {
	
	private int mWidthPixels;
	private int mXOffset;
	private int mCriticalValue;
	private boolean mMoved;
	private float mOx;
	private float mOy;
	private View mRightView;
	private OnMenuShowListener mListener;
	
	public interface OnMenuShowListener {
		
		void onMenuShow(RightMenuScrollView view);
	}
	
	public void setOnMenuShowListener(OnMenuShowListener listener) {
		
		mListener = listener;
	}
	
	public RightMenuScrollView(Context context) {
		
		this(context, null);
	}
	
	public RightMenuScrollView(Context context, AttributeSet attrs) {
		
		this(context, attrs, 0);
	}
	
	public RightMenuScrollView(Context context, AttributeSet attrs, int defStyle) {
		
		super(context, attrs, defStyle);
		mWidthPixels = getResources().getDisplayMetrics().widthPixels;
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		if (mRightView != null) {
			mCriticalValue = mRightView.getMeasuredWidth();
		}
	}
	
	//调用此方法，让左边的View占满屏幕，从而将右边View挤出到屏幕外
	public void setLeftRightView(View leftView, View rightView) {
		
		ViewGroup.LayoutParams layoutParams = leftView.getLayoutParams();
		layoutParams.width = mWidthPixels;
		leftView.setLayoutParams(layoutParams);
		
		mRightView = rightView;
	}
	
	public void restoreXOffset() {
		
		smoothScrollTo(0, 0);
	}
	
	@Override
	protected void onScrollChanged(int l, int t, int ol, int ot) {
		
		super.onScrollChanged(l, t, ol, ot);
		mXOffset = l;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		super.onTouchEvent(event);
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mOx = event.getX();
			mOy = event.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			mMoved = Math.abs(event.getX() - mOx) > 3 || Math.abs(event.getY() - mOy) > 3;
			break;
		case MotionEvent.ACTION_UP:
			if (!mMoved) {
				setScrollX(0);
				performClick();
			} else if (mXOffset >= mCriticalValue / 2.0) {
				smoothScrollTo(mWidthPixels + mCriticalValue, 0);
				if (mListener != null) {
					mListener.onMenuShow(this);
				}
			} else {
				smoothScrollTo(0, 0);
			}
			break;
		}
		return true;
	}
}